{% extends 'base.html' %}

{% block content %}
    <style>
        /* 全局样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            background-color: #121212; /* 深色背景 */
            color: #e0e0e0; /* 浅色文字 */
        }

        h1, h2 {
            color: #ffffff; /* 标题使用白色 */
        }

        /* 牌按钮部分 */
        .card-buttons {
            margin-bottom: 30px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: center;
        }

        .card-button {
            padding: 15px 20px;
            background-color: #3a3a3a; /* 深色按钮背景 */
            color: #ffffff; /* 按钮文字为白色 */
            border: none;
            border-radius: 8px;
            cursor: pointer;
            width: 80px;
            text-align: center;
            transition: background-color 0.3s;
            position: relative;
            font-size: 16px;
        }

        .card-button:hover {
            background-color: #555555; /* 悬停时按钮变亮 */
        }

        .card-button:disabled {
            background-color: #555555;
            cursor: not-allowed;
        }

        .card-count {
            position: absolute;
            top: 5px;
            right: 10px;
            background-color: #f44336; /* 红色背景 */
            color: #ffffff; /* 白色文字 */
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        /* 牌堆部分 */
        .deck {
            margin-bottom: 20px;
            text-align: center;
        }

        .deck table {
            width: 60%;
            border-collapse: collapse;
            background-color: #1e1e1e; /* 深色表格背景 */
            margin: 0 auto;
        }

        .deck th, .deck td {
            border: 1px solid #333333; /* 深色边框 */
            padding: 12px;
            text-align: center;
        }

        .deck th {
            background-color: #333333; /* 表头更深色 */
            color: #ffffff; /* 表头文字为白色 */
        }

        /* 操作按钮部分 */
        .actions {
            margin-bottom: 20px;
            text-align: center;
        }

        .actions button {
            padding: 10px 20px;
            margin: 0 10px;
            background-color: #3a3a3a; /* 深色按钮背景 */
            color: #ffffff; /* 按钮文字为白色 */
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
            font-size: 16px;
        }

        .actions button:hover {
            background-color: #555555; /* 悬停时按钮变亮 */
        }

        /* 出牌结果部分 */
        .play-result {
            margin-top: 20px;
            text-align: center;
        }

        .play-result ul {
            list-style-type: none;
            padding-left: 0;
            display: inline-block;
            text-align: left;
        }

        .play-result li {
            padding: 5px 0;
        }

        /* 消息和错误提示 */
        .message {
            color: #4caf50; /* 绿色用于成功消息 */
            margin-bottom: 20px;
            text-align: center;
        }

        .error {
            color: #f44336; /* 红色用于错误消息 */
            margin-bottom: 20px;
            text-align: center;
        }

        /* 自定义滚动条样式 */
        ::-webkit-scrollbar {
            width: 12px;
        }

        ::-webkit-scrollbar-track {
            background: #1e1e1e;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #555555;
            border-radius: 6px;
            border: 3px solid #1e1e1e;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .deck table {
                width: 100%;
            }

            .card-button {
                width: 60px;
                padding: 10px 15px;
                font-size: 14px;
            }

            .card-count {
                width: 18px;
                height: 18px;
                font-size: 10px;
            }

            .actions button {
                padding: 8px 16px;
                margin: 5px;
                font-size: 14px;
            }

            .play-result ul {
                width: 90%;
            }
        }

        #record-btn {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #ff5f5f, #ff1f1f);
            border-radius: 50%;
            border: none;
            cursor: pointer;
            outline: none;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: visible;
            transition: box-shadow 0.3s;
            margin-bottom: 20px;
        }

        #record-btn:hover {
            box-shadow: 0 0 15px rgba(255, 31, 31, 0.4);
        }

        #record-btn svg {
            fill: #fff;
            width: 30px;
            height: 30px;
            transition: transform 0.3s;
        }

        #record-btn.recording svg {
            transform: scale(1.2);
        }

        /* 脉冲动画 */
        #record-btn.recording::before, #record-btn.recording::after {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(255, 31, 31, 0.3);
            opacity: 0;
            animation: pulse 1.5s infinite;
        }

        #record-btn.recording::after {
            width: 140px;
            height: 140px;
            animation-delay: 0.75s;
        }

        @keyframes pulse {
            0% {
                transform: translate(-50%, -50%) scale(0.8);
                opacity: 0.5;
            }
            50% {
                transform: translate(-50%, -50%) scale(1.2);
                opacity: 0;
            }
            100% {
                transform: translate(-50%, -50%) scale(1.5);
                opacity: 0;
            }
        }
    </style>

    <body>
    <!-- 牌按钮部分 -->
    <div class="card-buttons" id="card-buttons">
        <!-- 动态生成的牌按钮 -->
    </div>
    <!-- 操作按钮部分 -->
    <div class="actions">
        <button id="reset-deck">重置牌堆</button>
        <button id="refresh-deck">刷新牌堆</button>
    </div>
    <center>
        <button id="record-btn" title="点击开始录音">
            <!-- 简单的麦克风SVG图标 -->
            <svg viewBox="0 0 24 24">
                <path d="M12 14c1.656854 0 3-1.343146 3-3V5c0-1.656854-1.343146-3-3-3s-3 1.343146-3 3v6c0 1.656854 1.343146 3 3 3zM18.5 11c0 3.038057-2.461943 5.5-5.5 5.5S7.5 14.038057 7.5 11H6c0 3.592839 2.666042 6.561127 6 6.95053V21h-3v2h8v-2h-3v-3.04947c3.333958-.389403 6-3.357691 6-6.95053h-1.5z"></path>
            </svg>
        </button>
        <p id="status">准备就绪</p>
        <!-- 消息和错误提示 -->
        <div class="message" id="message"></div>
        <div class="error" id="error"></div>
        <!-- 出牌结果部分 -->
        <div class="play-result">
            <div id="play-result"></div>
        </div>
    </center>
    <!-- 牌堆部分 -->
    <div class="deck">
        <table id="deck-table">
            <thead>
            <tr>
                <th>牌</th>
                <th>剩余数量</th>
            </tr>
            </thead>
            <tbody>
            <!-- 动态填充牌堆 -->
            </tbody>
        </table>
    </div>

    <!-- CSRF 令牌 -->
    {% csrf_token %}
    <script src="https://cdn.jsdelivr.net/gh/mattdiamond/Recorderjs@master/dist/recorder.js"></script>
    <script>
        let recorder;
        let audioStream;
        let isRecording = false;

        const recordBtn = document.getElementById('record-btn');
        const statusEl = document.getElementById('message');

        recordBtn.addEventListener('click', async () => {
            if (!isRecording) {
                // 开始录音
                statusEl.textContent = "请求麦克风权限...";
                try {
                    audioStream = await navigator.mediaDevices.getUserMedia({audio: true});
                    const audioContext = new AudioContext();
                    const input = audioContext.createMediaStreamSource(audioStream);

                    recorder = new Recorder(input, {numChannels: 1});
                    recorder.record();

                    recordBtn.classList.add('recording');
                    recordBtn.title = "点击停止录音并上传";
                    statusEl.textContent = "正在录音...";
                    isRecording = true;
                } catch (err) {
                    console.error(err);
                    statusEl.textContent = "无法访问麦克风：" + err.message;
                }
            } else {
                // 停止录音并上传
                recorder.stop();
                audioStream.getAudioTracks().forEach(track => track.stop());

                recordBtn.classList.remove('recording');
                recordBtn.title = "点击开始录音";
                statusEl.textContent = "正在处理音频...";
                isRecording = false;

                recorder.exportWAV(blob => {
                    statusEl.textContent = "上传中...";
                    uploadAudio(blob);
                });
            }
        });

        function uploadAudio(blob) {
            const formData = new FormData();
            formData.append('file', blob, 'recorded_audio.wav');

            fetch('/card/voice_search/', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        statusEl.textContent = "上传失败：" + data.error;
                    } else {
                        statusEl.textContent = `上传完成！识别结果: ${data.message}`;
                        if (data.play_result) {
                            let resultHtml = '<ul>';
                            data.play_result.forEach(result => {
                                if (result.status === 'played') {
                                    resultHtml += `<li>已出牌: ${result.card}，剩余: ${result.remaining}</li>`;
                                } else if (result.status === 'none_left') {
                                    resultHtml += `<li>牌 ${result.card} 已经没有剩余了。</li>`;
                                } else if (result.status === 'invalid') {
                                    resultHtml += `<li>无效的牌: ${result.card}</li>`;
                                }
                            });
                            resultHtml += '</ul>';
                            document.getElementById('play-result').innerHTML = resultHtml;
                        }
                        if (data.deck) {
                            updateDeckTable(data.deck);
                            updateCardButtons(data.deck);
                        }
                    }
                })
                .catch(err => {
                    statusEl.textContent = "上传失败：" + err.message;
                    console.error("Upload Error:", err);
                });
        }

        // 获取 CSRF 令牌
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        const csrftoken = getCookie('csrftoken');

        // 更新牌堆表格
        function updateDeckTable(deck) {
            const tbody = document.querySelector('#deck-table tbody');
            tbody.innerHTML = ''; // 清空现有内容
            for (const [card, count] of Object.entries(deck)) {
                const row = document.createElement('tr');
                const cardCell = document.createElement('td');
                cardCell.textContent = card;
                const countCell = document.createElement('td');
                countCell.textContent = count;
                row.appendChild(cardCell);
                row.appendChild(countCell);
                tbody.appendChild(row);
            }
        }

        // 更新牌按钮
        function updateCardButtons(deck) {
            const cardButtonsDiv = document.getElementById('card-buttons');
            cardButtonsDiv.innerHTML = ''; // 清空现有按钮

            for (const [card, count] of Object.entries(deck)) {
                // 创建按钮元素
                const button = document.createElement('button');
                button.classList.add('card-button');
                button.textContent = card;

                // 创建数量显示
                const countSpan = document.createElement('span');
                countSpan.classList.add('card-count');
                countSpan.textContent = count;
                button.appendChild(countSpan);

                // 如果没有剩余数量，禁用按钮
                if (count === 0) {
                    button.disabled = true;
                }

                // 添加点击事件
                button.addEventListener('click', () => {
                    playCard(card);
                });

                // 添加到容器
                cardButtonsDiv.appendChild(button);
            }
        }

        // 显示消息
        function showMessage(msg) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = msg;
            setTimeout(() => {
                messageDiv.textContent = '';
            }, 5000);
        }

        // 显示错误
        function showError(msg) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = msg;
            setTimeout(() => {
                errorDiv.textContent = '';
            }, 5000);
        }

        // 获取当前牌堆
        function fetchDeck() {
            fetch('/card/show_deck/')
                .then(response => response.json())
                .then(data => {
                    updateDeckTable(data.deck);
                    updateCardButtons(data.deck);
                })
                .catch(error => {
                    showError('获取牌堆失败。');
                    console.error('Error fetching deck:', error);
                });
        }

        // 重置牌堆
        function resetDeck() {
            fetch('/card/reset_deck/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken
                },
                body: JSON.stringify({})
            })
                .then(response => response.json())
                .then(data => {
                    if (data.message) {
                        showMessage(data.message);
                    }
                    if (data.deck) {
                        updateDeckTable(data.deck);
                        updateCardButtons(data.deck);
                    }
                })
                .catch(error => {
                    showError('重置牌堆失败。');
                    console.error('Error resetting deck:', error);
                });
        }

        // 刷新牌堆
        function refreshDeck() {
            fetchDeck();
        }

        // 记录出牌
        function playCard(card) {
            fetch('/card/play_cards/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken
                },
                body: JSON.stringify({cards: [card]})
            })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        showError(data.error);
                        return;
                    }
                    if (data.play_result) {
                        let resultHtml = '<ul>';
                        data.play_result.forEach(result => {
                            if (result.status === 'played') {
                                resultHtml += `<li>已出牌: ${result.card}，剩余: ${result.remaining}</li>`;
                            } else if (result.status === 'none_left') {
                                resultHtml += `<li>牌 ${result.card} 已经没有剩余了。</li>`;
                            } else if (result.status === 'invalid') {
                                resultHtml += `<li>无效的牌: ${result.card}</li>`;
                            }
                        });
                        resultHtml += '</ul>';
                        document.getElementById('play-result').innerHTML = resultHtml;
                    }
                    if (data.deck) {
                        updateDeckTable(data.deck);
                        updateCardButtons(data.deck);
                    }
                    showMessage(`已记录出牌: ${card}`);
                })
                .catch(error => {
                    showError('记录出牌失败。');
                    console.error('Error playing card:', error);
                });
        }

        // 绑定事件
        document.getElementById('reset-deck').addEventListener('click', resetDeck);
        document.getElementById('refresh-deck').addEventListener('click', refreshDeck);

        // 初始化时获取牌堆
        document.addEventListener('DOMContentLoaded', fetchDeck);
    </script>
    </body>
{% endblock %}
